<?php

namespace app\erp\model;

use think\Model;
use traits\model\SoftDelete;
use app\erp\validate\Goodsrule;
use think\Db;
use think\Cache;
use app\jun\controller\Api;

class Goodsdb extends Model
{
    use SoftDelete;

    protected $deleteTime = 'delete_time';
    protected $pk = 'goods_id';
    protected $name = 'goods';
    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i',
        'delete_time' => 'timestamp:Y-m-d',
        'update_time' => 'timestamp:Y-m-d H:i:s'
    ];
    protected $config_baojing = 0;
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;
    public $param = array();
    public $last_goods_sku = '';
    public $jun_push_result = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr ['partner_id'] = PARTNER_ID;
        if (!isset ($new_arr ['site_id'])) {
            $new_arr ['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }


    // 自动完成
    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id',
        'admin_id' => MEMBER_ID,
        'audit_state'
    ];
    // 注意 列表上修改可能要出问题
    protected $auto = [
        'is_real',
        'is_shopping',
        'is_install',
        'is_copy',
        'is_energy',
        'is_environmental'
    ];
    protected $update = [
        'api_get_edit' => 2,
        'api_get_add' => 2
    ];
    protected $get_site_id;


    /**
     * Title('校验品牌是否需要证书')
     */
    public function getChkBrandCertAttr($value, $row)
    {
        if ($row['jun_brandid']) {
            $brand_sign = Db::name('brand_api')->where('option', $row['jun_brandid'])->field('brand_sign,brand_name')->find();
            if ($brand_sign) {
                $get_brand = Db::name('brand')->where('brand_sign', $brand_sign['brand_sign'])->field('is_need_cert,is_white')->find();
                if ($get_brand) {
                    if ($get_brand['is_need_cert'] == 1) {
                        // 需要校验证书
                        $brandcertdb = new Brandcertdb();
                        if ($get_brand['is_white']) {
                            // 白名单 任何人上传都能用
                            $get_cert = $brandcertdb
                                ->where('audit_state', 1)
                                ->where('is_open', 1)
                                ->whereTime('end_date', '>', time())
                                ->where('brand_name', $brand_sign['brand_name'])
                                ->order('id desc')
                                ->select();
                        } else {
                            // 非白名单，只有自己能用
                            $get_cert = $brandcertdb
                                ->where('audit_state', 1)
                                ->where('supplier_id', MEMBER_ID)
                                ->where('is_open', 1)
                                ->whereTime('end_date', '>', time())
                                ->where('brand_name', $brand_sign['brand_name'])
                                ->order('id desc')
                                ->select();
                        }
                        if (!$get_cert->isEmpty()) {
                            $result = 2;
                            foreach ($get_cert as $key => $val) {
                                if ($val['goods']) {
                                    $temp_goods = explode(',', $val['goods']);
                                    if (in_array($row['jun_id'], $temp_goods)) {
                                        $result = 1;
                                    }
                                } else {
                                    if ($val['category_arr'] == 'all') {
                                        $result = 1;
                                    } else {
                                        $temp_cate = explode(',', $val['category_arr']);
                                        if (in_array($row['category_sign3'], $temp_cate)) {
                                            $result = 1;
                                        }
                                    }
                                }
                            }
                            return $result;
                        } else {
                            return 2;
                        }
                    } else {
                        return 0;
                    }

                } else {
                    return 0;
                }
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }


    /**
     * Title("获取管理部门")
     * Des("根据上传的品牌证书获取")
     */
    protected function manageDepartmentAttr($row)
    {
        $get_goods = Db::name('goods')->field('brand_sign,api_option')->find($row['goods_id']);
        $brand_name = '';
        $result = '';
        if (isset($get_goods['api_option']) && $get_goods['api_option']) {
            $get_option = json_decode($get_goods['api_option'], true);
            if (isset($get_option['brandid'])) {
                $brand_name = Db::name('brand_api')->where('option', $get_option['brandid'])->value('brand_name');
            }
        }
        if (!$brand_name && isset($row['brand_sign']) && $row['brand_sign']) {
            $brand_name = Db::name('brand')->where('brand_sign', $get_goods['brand_sign'])->value('brand_name');
        }

        if ($brand_name) {
            $chk_department = Db::name('brandcert')
                ->where('audit_state', 1)
                ->where('is_open', 1)
                ->whereTime('end_date', '>', time())
                ->where('brand_name', $brand_name)
                ->order('id desc')
                ->value('department');
            if ($chk_department) {
                $result = $chk_department;
            }
        }
        return $result;
    }


    protected function getZuidijiaAttr($value, $row)
    {
        $saledb = new SalePricedb();
        $get_price = 0;
        $get_price = $saledb->where('goods_sku', $row['goods_sku'])->value('zuidijia');
        return $get_price;
    }

    protected function setSiteIdAttr($value)
    {
        if (!$value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    protected function setAuditStateAttr($value)
    {
        if ($value) {
            return $value;
        } else {
            if (SITE_ID) {
                // 获取分站信息
                $sitedb = new Sitedb ();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site ['goods_audit'] == 1) {
                    return 0;
                } else {
                    return 1;
                }
            } else {
                return 1;
            }
        }
    }

    // 产品图片组
    public function setGoodsPicturesAttr($value)
    {
        if ($value) {
            if (is_array($value)) {
                return implode(',', $value);
            } else {
                return $value;
            }
        } else {
            return '';
        }
    }

    // 销售状态
    protected function setSaleStateAttr($value)
    {
        if (isset ($this->param ['sale_state']) && $this->param ['sale_state'] == 'on') {
            return 1;
        } else {
            if ($value) {
                return $value;
            } else {
                return 2;
            }
        }
    }

    // 复制信息
    protected function setIsCopyAttr($value)
    {
        if (isset ($this->param ['is_copy']) && $this->param ['is_copy'] == 'on') {
            return 1;
        } else {
            if ($value) {
                return $value;
            } else {
                return 2;
            }
        }
    }

    // 是否实物
    protected function setIsRealAttr($value)
    {
        if (isset ($this->param ['is_real']) && $this->param ['is_real'] == 'on') {
            return 1;
        } else {
            if ($value) {
                return $value;
            } else {
                return 2;
            }
        }
    }

    // 是否包邮
    protected function setIsShoppingAttr($value)
    {
        if (isset ($this->param ['is_shopping']) && $this->param ['is_shopping'] == 'on') {
            return 1;
        } else {
            if ($value) {
                return $value;
            } else {
                return 2;
            }
        }
    }

    // 安装
    protected function setIsInstallAttr($value)
    {
        if (isset ($this->param ['is_install']) && $this->param ['is_install'] == 'on') {
            return 1;
        } else {
            if ($value) {
                return $value;
            } else {
                return 2;
            }
        }
    }

    // 节能
    protected function setIsEnergyAttr($value)
    {
        if (isset ($this->param ['is_energy']) && $this->param ['is_energy'] == 'on') {
            return 1;
        } else {
            if ($value) {
                return $value;
            } else {
                return 2;
            }
        }
    }

    // 环保
    protected function setIsEnvironmentalAttr($value)
    {
        if (isset ($this->param ['is_environmental']) && $this->param ['is_environmental'] == 'on') {
            return 1;
        } else {
            if ($value) {
                return $value;
            } else {
                return 2;
            }
        }
    }

    public function scopeSelectGoodsSkus($query, $select_goods_skus)
    {
        if ($select_goods_skus == '') {
            $query->where('goods_sku', 0);
        } else {
            $query->where('goods_sku', 'IN', explode(',', $select_goods_skus));
        }
    }

    public function scopeNoSelectGoodsSkus($query, $no_select_goods_skus)
    {
        $query->where('goods_sku', 'NOT IN', explode(',', $no_select_goods_skus));
    }

    public function scopeGoodsSku($query, $goods_sku)
    {
        if (is_array($goods_sku)) {
            $query->where('goods_sku', 'IN', $goods_sku);
        } else {
            if (strlen($goods_sku) == 36 || strlen($goods_sku) == 19 || strlen($goods_sku) == 20) {
                $query->where('goods_sku', $goods_sku);
            } else {
                $query->where('goods_sku', 'like', '%' . $goods_sku . '%');
            }
        }
    }

    public function scopeSaleState($query, $sale_state)
    {
        if ($sale_state == '-1') {
            $query->whereIn('sale_state', [1, 2]);
        } else {
            $query->where('sale_state', $sale_state);
        }

    }

    public function scopeAuditState($query, $audit_state)
    {
        if ($audit_state == 2) {
            $audit_state = 0;
        }
        $query->where('audit_state', $audit_state);
    }

    // 分类查询
    public function scopeCategorySign($query, $category_sign)
    {
        $query->where('category_sign3', 'IN', $category_sign);
    }

    public function scopeGoodsName($query, $goods_name)
    {
        //$query->where('goods_name', 'like', '%' . $goods_name . '%');
        $query->where('goods_name', $goods_name);
    }

    public function scopePackingList($query, $packing_list)
    {
        $query->where('packing_list', 'like', '%' . $packing_list . '%');
    }

    public function scopeZiyingUrl($query, $ziying_url)
    {
        $query->where('ziying_url', $ziying_url);
    }

    public function scopeCategorySign1($query, $category_sign1)
    {
        $query->where('category_sign1', 'IN', $category_sign1);
    }

    public function scopeCategorySign2($query, $category_sign2)
    {
        $query->where('category_sign2', 'IN', $category_sign2);
    }

    public function scopeCategorySign3($query, $category_sign3)
    {
        if (!is_array($category_sign3)) {
            if (strpos(',', $category_sign3)) {
                $category_sign3 = explode(',', $category_sign3);
            }
        }
        $query->where('category_sign3', 'IN', $category_sign3);
    }

    public function scopeBrandSign($query, $brand_sign)
    {
        $temp = explode(',', $brand_sign);
        if (count($temp) > 1) {
            $query->where('brand_sign', 'IN', $temp);
        } else {
            $query->where('brand_sign', $brand_sign);
        }
    }

    public function scopeGoodsModel($query, $goods_model)
    {
        //$query->where('goods_model', $goods_model);
        $query->whereLike('goods_model', '%' . $goods_model . '%');

//		if (isset ( $this->param ['model_exact'] ) && $this->param ['model_exact'] == 'yes') {
//			$query->where ( 'goods_model', $goods_model );
//		} else {
//			$query->where ( 'goods_model', 'like', '%' . $goods_model . '%' );
//		}
    }

    public function scopeIsCopy($query, $is_copy)
    {
        $query->where('is_copy', $is_copy);
    }

    public function scopeCreateTimeStart($query, $create_time)
    {
        $query->whereTime('create_time', '>=', $create_time);
    }

    public function scopeCreateTimeEnd($query, $create_time)
    {
        $time = strtotime($create_time);
        $date = strtotime('+1 day', $time);
        $query->whereTime('create_time', '<', $date);
    }


    public function scopeKeywords($query, $keywords)
    {
        $query->where('goods_name', 'like', '%' . urldecode($keywords) . '%');
        $query->whereOr('jun_id', 'like', '%' . urldecode($keywords) . '%');
    }

    public function scopeApiGetAdd($query)
    {
        $query->where('api_get_add', 2);
    }

    public function scopeApiGetEdit($query)
    {
        $query->where('api_get_edit', 2);
    }

    public function scopeGoodsId($query, $goods_id)
    {
        $query->where('goods_id', $goods_id);
    }

    public function scopeOutGoodsSku($query, $out_goods_sku)
    {
        $query->where('out_goods_sku', $out_goods_sku);
    }

    public function scopeJunId($query, $jun_id)
    {
        if (is_array($jun_id)) {
            $query->where('jun_id', 'IN', $jun_id);
        } else {
            $query->where('jun_id', $jun_id);
        }
    }

    public function scopeMasterNo($query, $category_sign1, $category_sign2, $category_sign3)
    {
        $sql = 'select goods_sku from `ys_goods` where site_id is null and category_sign1="' . $category_sign1 . '" and category_sign2="' . $category_sign2 . '" and category_sign3="' . $category_sign3 . '"';
        $query->where('goods_sku', 'exp', 'not in(' . $sql . ')');
    }

    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset ($this->param ['delete']) && $this->param ['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        /*$query->where('ys_goods.partner_id', PARTNER_ID);
        if (isset ($this->param ['site_id'])) {
            if ($this->param ['site_id'] == 0 || $this->param ['site_id'] == '') {
                $query->where('ys_goods.site_id', 'null');
                $this->get_site_id = 'null';
            } elseif ($this->param ['site_id'] == -1) {
            } else {
                $query->where('ys_goods.site_id', $this->param ['site_id']);
                $this->get_site_id = $this->param ['site_id'];
            }
        } else {
            if (!empty (SITE_ID)) {
                $query->where('ys_goods.site_id', SITE_ID);
                $this->get_site_id = SITE_ID;
            } else {
                $query->where('ys_goods.site_id', 'null');
                $this->get_site_id = 'null';
            }
        }*/
        if (isset ($this->param ['admin_id']) && $this->param ['admin_id']) {
            $query->adminId($this->param ['admin_id']);
        }
        if (isset ($this->param ['pre_info']) && $this->param ['pre_info']) {
            $query->preInfo($this->param ['pre_info']);
        }
        if (isset ($this->param ['goods_sku']) && !empty ($this->param ['goods_sku'])) {
            $query->goodsSku($this->param ['goods_sku']);
        }
        if (isset ($this->param ['select_goods_skus'])) {
            $query->selectGoodsSkus($this->param ['select_goods_skus']);
        }
        if (isset ($this->param ['no_select_goods_skus']) && $this->param ['no_select_goods_skus'] != '') {
            $query->noSelectGoodsSkus($this->param ['no_select_goods_skus']);
        }

        if (isset ($this->param ['category_sign']) && $this->param ['category_sign']) {
            $query->categorySign($this->param ['category_sign']);
        }
        if (isset ($this->param ['goods_name']) && $this->param ['goods_name']) {
            $query->goodsName($this->param ['goods_name']);
        }
        if (isset ($this->param ['ziying_url']) && $this->param ['ziying_url']) {
            $query->ziyingUrl($this->param ['ziying_url']);
        }
        if (isset ($this->param ['ziying_sku']) && $this->param ['ziying_sku']) {
            $query->ziyingSku($this->param ['ziying_sku']);
        }
        if (isset ($this->param ['category_sign1']) && $this->param ['category_sign1']) {
            if (!isset ($this->param ['category_sign2']) || !$this->param ['category_sign2']) {
                $query->categorySign1($this->param ['category_sign1']);
            }
        }
        if (isset ($this->param ['category_sign2']) && $this->param ['category_sign2']) {
            if (!isset ($this->param ['category_sign3']) || !$this->param ['category_sign3']) {
                $query->categorySign2($this->param ['category_sign2']);
            }
        }
        if (isset ($this->param ['category_sign3']) && $this->param ['category_sign3']) {
            $query->categorySign3($this->param ['category_sign3']);
        }
        if (isset ($this->param ['brand_sign']) && $this->param ['brand_sign']) {
            $query->brandSign($this->param ['brand_sign']);
        }
        if (isset ($this->param ['goods_model']) && $this->param ['goods_model']) {
            $query->goodsModel($this->param ['goods_model']);
        }
        if (isset ($this->param ['jun_id']) && $this->param ['jun_id']) {
            $query->junId($this->param ['jun_id']);
        }
        if (isset ($this->param ['jun_state']) && $this->param ['jun_state']) {
            $query->junState($this->param ['jun_state']);
        }
        if (isset ($this->param ['is_copy']) && $this->param ['is_copy']) {
            $query->isCopy($this->param ['is_copy']);
        }
        if (isset ($this->param ['goods_id']) && $this->param ['goods_id']) {
            $query->goodsId($this->param ['goods_id']);
        }
        if (isset ($this->param ['is_lock']) && $this->param ['is_lock']) {
            $query->isLock($this->param ['is_lock']);
        }
        if (isset ($this->param ['create_time_start']) && $this->param ['create_time_start']) {
            $query->createTimeStart($this->param ['create_time_start']);
        }
        if (isset ($this->param ['create_time_end']) && $this->param ['create_time_end']) {
            $query->createTimeEnd($this->param ['create_time_end']);
        }
        if (isset ($this->param ['keywords']) && $this->param ['keywords']) {
            $query->keywords($this->param ['keywords']);
        }
        if (isset ($this->param ['packing_list']) && $this->param ['packing_list']) {
            $query->packingList($this->param ['packing_list']);
        }
        if (isset ($this->param ['api_get_add']) && $this->param ['api_get_add'] == 'yes') {
            $query->apiGetAdd();
        }
        if (isset ($this->param ['api_get_edit']) && $this->param ['api_get_edit'] == 'yes') {
            $query->apiGetEdit();
        }
        if (isset ($this->param ['out_goods_sku']) && $this->param ['out_goods_sku']) {
            $query->outGoodsSku($this->param ['out_goods_sku']);
        }
        if (isset ($this->param ['master_no']) && $this->param ['master_no'] == 'yes') {
            $query->masterNo($this->param ['category_sign1'], $this->param ['category_sign2'], $this->param ['category_sign3']);
        }


        if (isset ($this->param ['is_push']) && $this->param ['is_push']) {
            $query->isPush($this->param ['is_push']);
        }
        if (isset ($this->param ['min_price']) && $this->param ['min_price']) {
            $query->where('sale_price', '>=', $this->param ['min_price']);
        }
        if (isset ($this->param ['max_price']) && $this->param ['max_price']) {
            $query->where('sale_price', '<=', $this->param ['max_price']);
        }
        if (isset ($this->param ['min_api_price']) && $this->param ['min_api_price']) {
            $query->where('api_price', '>=', $this->param ['min_api_price']);
        }
        if (isset ($this->param ['max_api_price']) && $this->param ['max_api_price']) {
            $query->where('api_price', '<=', $this->param ['max_api_price']);
        }
        if (isset ($this->param ['check_price']) && $this->param ['check_price']) {
            $query->checkPrice();
        }
        if (isset ($this->param ['susername']) && $this->param ['susername']) {
            $query->susername($this->param ['susername']);
        }

        if (isset ($this->param ['jun_price_flag']) && $this->param ['jun_price_flag']) {
            $query->junPriceFlag($this->param ['jun_price_flag']);
        }

        if (isset ($this->param ['sale_state']) && $this->param ['sale_state']) {
            $query->saleState($this->param ['sale_state']);
        }
        if (isset ($this->param ['audit_state']) && $this->param ['audit_state']) {
            $query->auditState($this->param ['audit_state']);
        }
    }

    public function scopeJunPriceFlag($query, $jun_price_flag)
    {
        $query->where('jun_price_flag', $jun_price_flag);
    }

    public function scopeCheckPrice($query)
    {
        $query->where('', 'exp', '(sale_price - api_price)/sale_price >0.1');
    }

    public function scopeIsPush($query, $is_push)
    {
        $query->where('is_push', $is_push);
    }

    public function scopeJunState($query, $jun_state)
    {
        $query->where('jun_state', $jun_state);
    }

    public function scopeIsLock($query, $is_lock)
    {
        $query->where('is_lock', $is_lock);
    }

    public function scopeAdminId($query, $admin_id)
    {
        $query->where('admin_id', $admin_id);
    }

    public function scopePreInfo($query, $pre_info)
    {
        /*if ($pre_info == 'utec') {
            $query->where('goods.goods_sku', 'like', 'SKU%');
        } else {
            $query->where('goods.goods_sku', 'not like', 'SKU%');
        }*/
        if ($pre_info == 'utec') {
            $query->where('goods.callet_juncai', 0);
        } elseif ($pre_info == 'jun') {
            $query->where('goods.callet_juncai', 1);
        }
    }

    public function scopeSusername($query, $susername)
    {
        $memberdb = new Memberdb ();
        $get_supplier_id = $memberdb->useGlobalScope(false)->where('supplier_name|username', 'like', '%' . $susername . '%', 'or')->select();
        if (!$get_supplier_id->isEmpty()) {
            $member_ids = array();
            $get_supplier_id = $get_supplier_id->toArray();
            foreach ($get_supplier_id as $key => $val) {
                array_push($member_ids, $val ['member_id']);
            }
            $query->where('admin_id', 'IN', $member_ids);
        } else {
            $query->where('admin_id', -1);
        }
    }

    // 复制
    public function copy()
    {
        $data = $this->select();
        if ($data) {
            $data = $data->toArray();
            $add_data = array();
            $goods_sku_arr = array();
            if (!isset ($this->param ['select_site_id']) || $this->param ['select_site_id'] == '') {
                $this->param ['site_id'] = SITE_ID;
                $this->param ['select_site_id'] = SITE_ID;
            } else {
                $this->param ['site_id'] = $this->param ['select_site_id'];
            }
            foreach ($data as $key => $val) {
                unset ($val ['goods_id']);
                unset ($val ['create_time']);
                unset ($val ['admin_id']);
                unset ($val ['update_time']);
                $val ['site_id'] = $this->param ['site_id'];
                $add_data [$key] = $val;
                array_push($goods_sku_arr, $val ['goods_sku']);
            }
            $this->ajaxDelete();
            $this->saveAll($add_data);
            // 同步销售属性
            $saleAttrdb = new SaleAttrdb ();
            $saleAttrdb->param ['site_id'] = 0;
            $saleAttrdb->param ['goods_sku'] = $goods_sku_arr;
            $saleAttrdb->param ['select_site_id'] = $this->param ['select_site_id'];

            $saleAttrdb->copy();
            // 同步销售属性值
            $salePricedb = new SalePricedb ();
            $salePricedb->param ['site_id'] = 0;
            $salePricedb->param ['goods_sku'] = $goods_sku_arr;
            $salePricedb->param ['select_site_id'] = $this->param ['select_site_id'];
            $salePricedb->copy();

            // 同步产品属性值
            $attrValuedb = new AttrValuedb ();
            $attrValuedb->param ['site_id'] = 0;
            $attrValuedb->param ['goods_sku'] = $goods_sku_arr;
            $attrValuedb->param ['select_site_id'] = $this->param ['select_site_id'];
            $attrValuedb->copy();
            foreach ($data as $key => $val) {
                // 新增 写推送通知
                $postNoticedb = new PostNoticedb ();
                $postNoticedb->param ['post_type'] = 6;
                $postNoticedb->param ['sku_order_no'] = $val ['goods_sku'];
                $postNoticedb->param ['new_data'] = 1;
                $postNoticedb->param ['site_id'] = $this->param ['select_site_id'];
                $postNoticedb->ajaxSave();
                $this->writePriceRecord($val ['goods_sku']);
            }
        }
        Cache::clear();
        return 'success';
    }

    // 采集
    public function collect()
    {
        $data = $this->select();

        if ($data) {
            $data = $data->toArray();
            $add_data = array();
            $goods_sku_arr = array();
            foreach ($data as $key => $val) {
                unset ($val ['goods_id']);
                unset ($val ['create_time']);
                unset ($val ['admin_id']);
                unset ($val ['update_time']);
                $val ['site_id'] = '';
                $add_data [$key] = $val;
                array_push($goods_sku_arr, $val ['goods_sku']);
            }
            $this->saveAll($add_data);
            // 同步销售属性
            $saleAttrdb = new SaleAttrdb ();
            $saleAttrdb->param ['site_id'] = $this->param ['site_id'];
            $saleAttrdb->param ['goods_sku'] = $goods_sku_arr;
            $saleAttrdb->collect();

            // 同步销售属性值
            $salePricedb = new SalePricedb ();
            $salePricedb->param ['site_id'] = $this->param ['site_id'];
            $salePricedb->param ['goods_sku'] = $goods_sku_arr;
            $salePricedb->collect();

            // 同步产品属性值
            $attrValuedb = new AttrValuedb ();
            $attrValuedb->param ['site_id'] = $this->param ['site_id'];
            $attrValuedb->param ['goods_sku'] = $goods_sku_arr;
            $attrValuedb->collect();
            foreach ($data as $key => $val) {
                // 新增 写推送通知
                $postNoticedb = new PostNoticedb ();
                $postNoticedb->param ['post_type'] = 6;
                $postNoticedb->param ['sku_order_no'] = $val ['goods_sku'];
                $postNoticedb->param ['new_data'] = 1;
                $postNoticedb->ajaxSave();
                $this->writePriceRecord($val ['goods_sku']);
            }
        }
        Cache::clear();
        return 'success';
    }

    // 查询
    public function ajaxSelect()
    {
        $return ['data'] = $this->ajaxList();
        $return ['count'] = $this->ajaxCount();
        return $return;
    }

    // 多商品图片
    public function pictureList()
    {
        $data = $this->cache($this->cache_name('goods_list'), 86400, 'goods')->select();
        if (!$data->isEmpty()) {
            $data = $data->toArray();
            $uploaddb = new Uploaddb ();
            foreach ($data as $key => $val) {
                $temp = explode(',', $val ['goods_pictures']);
                $data [$key] ['goods_pictures'] = $uploaddb->getSelect($temp);
            }
            return $data;
        }
        return '';
    }

    public function ajaxSku()
    {
        $data = $this->select();
        if (!$data->isEmpty()) {
            $data->toArray();
            $skus = array();
            foreach ($data as $key => $val) {
                array_push($skus, $val ['goods_sku']);
            }
            return $skus;
        } else {
            return '';
        }
    }

    public function ajaxList()
    {
        $siteconfigdb = new SiteConfigdb ();
        $siteconfigdb->param ['config_name'] = 'BAOJING';
        $get_config_baojing = $siteconfigdb->getValue();
        $this->config_baojing = $get_config_baojing;
        switch ($this->param ['_o']) {
            case 'brand_name' :
                $this->order('brand_sign', $this->param ['_b']);
                break;
            case 'category_name' :
                $this->order('category_sign3', $this->param ['_b']);
                break;
            default :
                $this->order($this->param ['_o'], $this->param ['_b']);
                break;
        }
        /*
         * if (isset ( $this->param ['check_price'] )) {
         * $get_sku = Db::name ( 'salePrice' )->field ( 'goods_sku' )->where ( 'site_id', SITE_ID )->where ( '(sale_price - api_price)/sale_price<=0.1' )->order('sale_price_id asc')->page ( $this->param ['page'], $this->param ['limit'] )->select ();
         * $sku_arr = array ();
         * if ($get_sku) {
         * $get_sku = $get_sku->toArray ();
         * foreach ( $get_sku as $key => $val ) {
         * array_push ( $sku_arr, $val ['goods_sku'] );
         * }
         * }
         * $data = $this->useGlobalScope ( 'false' )->where ( 'goods_sku', 'IN', implode ( ',', $sku_arr ) )->select ();
         * } else {
         */
        if (isset($this->param['select_goods_skus'])) {
            $data = $this->alias('goods')
                //Db::name('goods')
                //->fetchSql(true)
                ->field('goods_id,create_time,goods_sku,goods_unit,goods_name,goods_son_name,goods_model,goods_keywords,goods_intro,view_times,sale_num,goods_picture,goods_pictures,admin_id,sale_state,audit_state,category_sign1,category_sign2,category_sign3,brand_sign,weight,is_real,is_shopping,is_install,is_copy,api_get_add,api_get_edit,last_sale_state,out_goods_sku,packing_list,is_energy,is_environmental,product_area,product_firm,upc,energy_cert_no,energy_cert_image,energy_cert_indate,environment_protect_cert_no,environment_protect_cert_image,environment_protect_cert_indate,guimo,shenming,callet_juncai,is_push,is_lock,lock_open_time,sale_price,api_price,jun_id,shuiwu_id,jun_price_flag,good_type,jun_brandid,ziying_url,ziying_sku,is_zhongdian,is_ct,view_stock,jun_state,details,audit_remark,jun_update,invoice_model,audit_goods,junsale_state,zhenshi,operatedate,fenlei_name,pinpai_name,push_jun_result,goods_beizhu1,goods_beizhu2,goods_beizhu3,goods_beizhu4,goods_beizhu5,goods_beizhu6,goods_beizhu7,goods_beizhu8,goods_beizhu9,goods_beizhu10,goods_beizhu11,goods_beizhu12,goods_beizhu13,goods_beizhu14,goods_beizhu15,jd_goods_sku,jun_last_stock,jun_last_time')
                ->whereIn('goods_sku', $this->param['select_goods_skus'])
                ->select();
        } else {
            $data = $this->alias('goods')
                ->cache($this->cache_name('goods_list'), 86400, 'goods')
                //->fetchSql(true)
                ->page($this->param ['page'], $this->param ['limit'])
                ->select();
        }

        // }


        if (!$data->isEmpty()) {
            //$data = $data->hidden(['goods_content'])->toArray();
            $data = $data->append(['chk_brand_cert'])->toArray();
            if (!isset ($this->param ['no_need_handle_data'])) {
                foreach ($data as $key => $val) {
                    $data [$key] = $this->handleData($val);
                }
            } else {
                if (isset ($this->param ['need_cover'])) {
                    $uploaddb = new Uploaddb ();
                    $salePricedb = new SalePricedb ();
                    foreach ($data as $key => $val) {
                        $temp = explode(',', $val ['goods_pictures']);
                        $data [$key] ['goods_picture'] = $uploaddb->getFind($temp [0]);
                        // 获取前端显示价格
                        $salePricedb->param ['goods_sku'] = $val ['goods_sku'];
                        if (isset ($this->param ['no_more_price'])) {
                            $salePricedb->param ['no_more_price'] = $this->param ['no_more_price'];
                        }
                        $data [$key] ['sale_price_info'] = $salePricedb->ajaxSelect();

                        $data [$key] ['market_price'] = $data [$key] ['sale_price_info'] ['min_market_price'];
                        $data [$key] ['sale_price'] = $data [$key] ['sale_price_info'] ['min_sale_price'];
                        $data [$key] ['api_price'] = $data [$key] ['sale_price_info'] ['min_api_price'];
                        $data [$key] ['caigoujia'] = $data [$key] ['sale_price_info'] ['caigoujia'];
                        $data [$key] ['zuidijia'] = $data [$key] ['sale_price_info'] ['zuidijia'];
                        $data [$key] ['jun_zuidijia'] = $data [$key] ['sale_price_info'] ['jun_zuidijia'];
                        $data [$key] ['chengbenjia'] = $data [$key] ['sale_price_info'] ['chengbenjia'];
                        $data [$key] ['view_stock'] = $data [$key] ['sale_price_info'] ['view_stock'];
                        $data [$key] ['beizhu'] = $data [$key] ['sale_price_info'] ['beizhu'];
                    }
                }
            }
            if (isset($this->param['order_no'])) {
                foreach ($data as $key => $val) {
                    $get_goods_beizhu3 = Db::name('cart')->where('order_no', $this->param['order_no'])->where('goods_sku', $val['goods_sku'])->value('goods_beizhu3');
                    $data[$key]['cart_goods_beizhu'] = $get_goods_beizhu3 ?: $val['goods_beizhu3'];
                }
            }
        }

        return $data;
    }

    public function ajaxCount()
    {
        //return 1000000;
        return $this->alias('goods')->count();
    }

    // 根据第三方sku获取本地sku
    public function ajaxApiFind()
    {
        // $data = $this->where('out_goods_sku',$this->param['out_goods_sku'])->find();
        $data = $this->find();
        if ($data) {
            $data = $data->toArray();
            $data = $this->handleData($data);
        } else {
            $data = array();
        }
        return $data;
    }

    public function ajaxFindField($goods_sku, $site_id, $field)
    {
        $data = $this->useGlobalScope(false)->where('goods_sku', $goods_sku)->where('site_id', $site_id)->field($field)->find()->toArray();
        return $data;
    }

    public function ajaxApiFindPrice()
    {
        $data = $this->useGlobalScope(false)->where('goods_sku', $this->param ['goods_sku'])->whereNull('delete_time')->master()->find();
        if ($data) {
            $data = $data->toArray();
            if (isset ($this->param ['api_get_add_set'])) {
                $goods_sku = $this->param ['goods_sku'];
                $this->update = array();
                $this->save(array(
                    'api_get_add' => 1,
                    'api_get_edit' => 1
                ), array(
                    'goods_id' => $data ['goods_id']
                ));
                Cache::clear('goods');
            }
            $salePricedb = new SalePricedb ();
            // 获取前端显示价格
            $salePricedb->param ['goods_sku'] = $data ['goods_sku'];
            if (isset ($this->param ['site_id']) && $this->param ['site_id'] == -1) {
                $salePricedb->param ['site_id'] = $data ['site_id'];
            } else {
                $salePricedb->param ['site_id'] = $this->get_site_id;
            }
            if (isset ($this->param ['the_goods_site'])) {
                $salePricedb->param ['site_id'] = $data ['site_id'];
            }
            if (isset ($this->param ['no_more_price'])) {
                $salePricedb->param ['no_more_price'] = $this->param ['no_more_price'];
            }
            $data ['sale_price_info'] = $salePricedb->ajaxSelect();
            $data ['market_price'] = $data ['sale_price_info'] ['min_market_price'];
            $data ['sale_price'] = $data ['sale_price_info'] ['min_sale_price'];
            $data ['api_price'] = $data ['sale_price_info'] ['min_api_price'];
            $data ['view_stock'] = $data ['sale_price_info'] ['view_stock'];
        }
        return $data;
    }

    public function ajaxFind()
    {

        if (isset ($this->param ['goods_sku'])) {
            if (is_numeric($this->param ['goods_sku'])) {
                $data = $this->useGlobalScope(false)
                    //->fetchSql(true)
                    ->where('goods_id', $this->param ['goods_sku'])
                    ->whereNull('delete_time')
                    ->master()
                    ->find();
            } else {
                $data = $this->useGlobalScope(false)
                    //->fetchSql(true)
                    ->where('goods_sku', $this->param ['goods_sku'])
                    ->whereNull('delete_time')
                    ->master()
                    ->find();
            }
            //halt($data);

            if ($data) {
                $data->append(['brand_name']);
                $data = $data->toArray();

                if (isset ($this->param ['api_get_add_set'])) {
                    $goods_sku = $this->param ['goods_sku'];
                    $this->update = array();
                    $this->save(array(
                        'api_get_add' => 1,
                        'api_get_edit' => 1
                    ), array(
                        'goods_id' => $data ['goods_id']
                    ));
                    Cache::clear('goods');
                }
                if (!isset ($this->param ['no_need_goods_handle'])) {
                    $data = $this->handleData($data);
                } else {
                    // 获取前端显示价格
                    $salePricedb = new SalePricedb ();
                    $salePricedb->param ['goods_sku'] = $data ['goods_sku'];
                    if (isset ($this->param ['site_id']) && $this->param ['site_id'] == -1) {
                        $salePricedb->param ['site_id'] = $data ['site_id'];
                    } else {
                        $salePricedb->param ['site_id'] = $data ['site_id'];
                    }
                    if (isset ($this->param ['the_goods_site'])) {
                        $salePricedb->param ['site_id'] = $data ['site_id'];
                    }
                    if (isset ($this->param ['no_more_price'])) {
                        $salePricedb->param ['no_more_price'] = $this->param ['no_more_price'];
                    }
                    $get_sale_price = $salePricedb->useGlobalScope(false)->where('goods_sku', $data ['goods_sku'])->find();
                    $data ['market_price'] = 0;
                    $data ['sale_price'] = 0;
                    $data ['api_price'] = 0;
                    $data ['view_stock'] = 0;
                    if ($get_sale_price) {
                        $get_sale_price = $get_sale_price->toArray();
                        $data ['market_price'] = $get_sale_price ['market_price'];
                        $data ['sale_price'] = $get_sale_price ['sale_price'];
                        $data ['api_price'] = $get_sale_price ['api_price'];
                        $data ['view_stock'] = $get_sale_price ['view_stock'];
                    }
                    // $sale_price = $salePricedb->ajaxFind ();
                }
                if (isset ($this->param ['need_covers'])) {
                    $uploaddb = new Uploaddb ();
                    if ($data['goods_picture']) {
                        $p_id = $data['goods_picture'];
                    } else {
                        $temp = explode(',', $data['goods_pictures']);
                        $p_id = temp[0];
                    }

                    $f = $uploaddb->getFind($p_id);
                    if ($f) {
                        $data ['goods_picture'] = $f['save_path'];
                    }
                }
                if (isset ($this->param ['need_cover'])) {
                    $uploaddb = new Uploaddb ();
                    if ($data['goods_picture']) {
                        $img_id = $data['goods_picture'];
                    } else {
                        $temp = explode(',', $data ['goods_pictures']);
                        $img_id = $temp[0];
                    }

                    $data ['goods_picture'] = $uploaddb->getFind($img_id);
                }

                if (!isset ($this->param ['no_need_attr'])) {
                    // 分类属性值
                    $attrValuedb = new AttrValuedb ();
                    $data ['attr_value'] = $attrValuedb->ajaxSelect($this->param ['goods_sku']);
                    // 分类属性
                    $attrdb = new Attrdb ();
                    $attrdb->param ['category_sign'] = $data ['category_sign3'];
                    $category_attr = $attrdb->ajaxList();
                    $attr_arr = array();
                    $temp = array();
                    foreach ($category_attr as $key => $val) {
                        $attr_arr [$key] ['group_name'] = $val ['group_name'];
                        $attr_arr [$key] ['attr_name'] = $val ['attr_name'];
                        if (isset ($data ['attr_value'] [$val ['attr_sign']])) {
                            $attr_arr [$key] ['attr_value'] = $data ['attr_value'] [$val ['attr_sign']];
                        } else {
                            $attr_arr [$key] ['attr_value'] = '';
                        }
                    }
                    $data ['goods_attr'] = $attr_arr;
                    // 销售属性
                    $saleAttrdb = new SaleAttrdb ();
                    $data ['sale_attr'] = $saleAttrdb->ajaxSelect($this->param ['goods_sku']);
                }
            } else {
                $data ['goods_sku'] = $this->param ['goods_sku'];
            }
        } else {
            $data ['goods_sku'] = 'SKU' . base_convert(uniqid(), 16, 10);
        }
        return $data;
    }

    public function chkGoodsModel()
    {
        $data = $this->find();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = array();
        }
        return $data;
    }

    // 保存多个数据 单个属性
    public function aloneSave($data, $where)
    {
        $this->save($data, $where);
        $get_key = array_keys($data);
        Cache::clear('goods');
        return 'success';
    }

    public function getGoodsViewTimes($goods_id)
    {
        $data = $this->useGlobalScope(false)->where('goods_id', $goods_id)->field('view_times')->find();
        if ($data) {
            $data = $data->toArray();
            return $data ['view_times'];
        } else {
            return 0;
        }
    }

    // 保存单个数据
    public function ajaxSaveOne($field, $value)
    {
        $getGoods = $this->find()->toArray();
        $this->auto = array();
        $this->isUpdate(true)->save(array(
            $field => $value
        ), [
            'goods_id' => $getGoods ['goods_id']
        ]);
        Cache::clear('goods');
    }

    // 保存销量
    public function ajaxSaveSaleNum()
    {
        $getGoods = $this->ajaxFind();
        $this->auto = array();
        $this->isUpdate(true)->save(array(
            'sale_num' => $getGoods ['sale_num'] + $this->param ['add_sale_num']
        ), [
            'goods_id' => $getGoods ['goods_id']
        ]);
        Cache::clear('goods');
    }

    // 转移产品
    public function ajaxTransfer($category_sign1, $category_sign2, $category_sign3, $goods_ids)
    {
        $this->param ['goods_ids'] = $goods_ids;
        $this->auto = array();

        $this->isUpdate(true)->save([
            'category_sign1' => $category_sign1,
            'category_sign2' => $category_sign2,
            'category_sign3' => $category_sign3
        ], function ($query) {
            $query->where('goods_id', 'IN', $this->param ['goods_ids']);
        });
        Cache::clear('goods');
        return 'success';
    }

    // 河南产品保存
    public function ajaxSaveHenan()
    {
        $rule = new Goodsrule ();
        $this->param ['partner_id'] = PARTNER_ID;
        $this->param ['site_id'] = $this->param ['site_id'];
        $this->param ['goods_sku'] = 'HN' . base_convert(uniqid(), 16, 10);
        $this->last_goods_sku = $this->param ['goods_sku'];
        $this->param ['weight'] = 0;
        $this->param ['sale_state'] = 1;
        if (!$rule->check($this->param)) {
            return $rule->getError();
        }
        // 获取分类
        $categorydb = new Categorydb ();
        $categorydb->param ['api_option'] = $this->param ['category_api'];
        $get_cotegory = $categorydb->ajaxTreeFind();
        if (!$get_cotegory) {
            return '未找到分类，编号：' . $this->param ['category_api'];
        }
        $this->param ['category_sign1'] = $get_cotegory ['category_sign1'];
        $this->param ['category_sign2'] = $get_cotegory ['category_sign2'];
        $this->param ['category_sign3'] = $get_cotegory ['category_sign3'];
        $this->param ['api_option'] = json_encode($this->param ['api_option']);
        // 开始保存数据 采用事务功能
        Db::startTrans();
        $this->save($this->param, false);
        // 保存分类属性值
        $attrValuedb = new AttrValuedb ();
        $attr_data = array();
        $i = 0;
        foreach ($this->param ['category_attr'] as $key => $val) {
            $attr_data [$i] ['site_id'] = $this->param ['site_id'];
            $attr_data [$i] ['goods_sku'] = $this->param ['goods_sku'];
            $attr_data [$i] ['attr_sign'] = $val ['cssm'];
            $attr_data [$i] ['attr_value'] = $val ['csz'];
            $i++;
        }
        $attrValuedb->param = $attr_data;
        $return = $attrValuedb->ajaxApiSaveAll();
        if ($return != 'success') {
            Db::rollback();
            return $return;
        }
        // 保存商品价格
        $salePricedb = new SalePricedb ();
        $salePricedb->param ['sale_attr_price_name'] [0] = '商品价格';
        $salePricedb->param ['goods_sku'] = $this->param ['goods_sku'];
        $salePricedb->param ['market_price'] [0] = 0;
        $salePricedb->param ['sale_price'] [0] = 0;
        $salePricedb->param ['api_price'] [0] = 0;
        $salePricedb->param ['give_score'] [0] = 0;
        $salePricedb->param ['view_stock'] [0] = 9999;
        $salePricedb->param ['last_api_price'] [0] = 0;
        $salePricedb->param ['site_id'] = $this->param ['site_id'];
        $salePricedb->param ['category_sign3'] = $this->param ['category_sign3'];
        $return = $salePricedb->ajaxSave();
        if ($return != 'success') {
            Db::rollback();
            return $return;
        }
        Db::commit();
        Cache::clear('goods');
        return 'success';
    }

    // 河南保存
    public function ajaxUpdateHenan()
    {
        $before_data = $this->ajaxFind($this->param ['goods_sku']);
        $this->last_goods_sku = $this->param ['goods_sku'];
        Db::startTrans();
        // 保存当前信息
        $this->allowField(true)->save($this->param, [
            'goods_id' => $this->param ['goods_id']
        ]);
        // 保存销售价格
        $salePricedb = new SalePricedb ();
        $this->param ['site_id'] = SITE_ID;
        $salePricedb->param = $this->param;
        $return = $salePricedb->ajaxSave();
        // 保存配件价格
        if (isset ($this->param ['accessory_price'])) {
            $goodsAccessorydb = new GoodsAccessorydb ();
            $accessory_data = array();
            for ($i = 0; $i < count($this->param ['accessory_price']); $i++) {
                $accessory_data [$i] ['goods_accessory_id'] = $this->param ['goods_accessory_id'] [$i];
                $accessory_data [$i] ['accessory_price'] = $this->param ['accessory_price'] [$i];
                $accessory_data [$i] ['last_accessory_price'] = $this->param ['last_accessory_price'] [$i];
            }
            $goodsAccessorydb->param ['data'] = $accessory_data;
            $return = $goodsAccessorydb->ajaxUpdateAll();
            if ($return != 'success') {
                Db::rollback();
                return $return;
            }
        }
        if (isset ($this->param ['service_price'])) {
            // 保存服务价格
            $goodsServicedb = new GoodsServicedb ();
            $service_data = array();
            for ($i = 0; $i < count($this->param ['service_price']); $i++) {
                $service_data [$i] ['goods_service_id'] = $this->param ['goods_service_id'] [$i];
                $service_data [$i] ['service_price'] = $this->param ['service_price'] [$i];
                $service_data [$i] ['last_service_price'] = $this->param ['last_service_price'] [$i];
            }
            $goodsServicedb->param ['data'] = $service_data;
            $return = $goodsServicedb->ajaxUpdateAll();
            if ($return != 'success') {
                Db::rollback();
                return $return;
            }
        }

        $this->writePriceRecord($this->param ['goods_sku']);
        // 写推送通知
        // 修改价格
        if (number_format($this->param ['api_price'] [0], 2, '.', '') != number_format($before_data ['api_price'], 2, '.', '')) {
            $this->allowField(true)->save([
                'audit_state' => 0
            ], [
                'goods_id' => $this->param ['goods_id']
            ]);
            // 分站修改数据需要审核
            $sitedb = new Sitedb ();
            $get_site = $sitedb->ajaxFind(SITE_ID);
            if ($get_site ['goods_audit'] == 1) {
                $auditdb = new Auditdb ();
                $auditdb->param ['audit_method'] = 3;
                if (isset ($this->param ['goods_id']) && $this->param ['goods_id'] != '') {
                    $auditdb->param ['audit_type'] = 2;
                } else {
                    $auditdb->param ['audit_type'] = 1;
                }
                $auditdb->param ['site_id'] = SITE_ID;
                $auditdb->param ['before_option'] = $before_data;
                $auditdb->param ['old_option'] = json_encode($before_data);
                // $auditdb->param['save_option'] = json_encode($this->param);
                $after_data = $this->ajaxFind($this->param ['goods_sku']);
                $auditdb->param ['after_option'] = $after_data;
                $auditdb->param ['audit_sign'] = $this->param ['goods_sku'];
                $audit_state = $auditdb->ajaxSave();
                if ($audit_state == 'fail') {
                    $this->save([
                        'audit_state' => $before_data ['audit_state']
                    ], [
                        'goods_id' => $before_data ['goods_id']
                    ]);
                }
            }
            $postNoticedb = new PostNoticedb ();
            $postNoticedb->param ['post_type'] = 2;
            $postNoticedb->param ['sku_order_no'] = $this->param ['goods_sku'];
            $postNoticedb->param ['old_data'] = number_format($this->param ['api_price'] [0], 2, '.', '');
            $postNoticedb->param ['new_data'] = $this->param ['market_price'] [0];
            $postNoticedb->ajaxSave();
        }

        Db::commit();
        Cache::clear('goods');

        return 'success';
    }

    // 保存军采采集
    public function ajaxSaveJuncai()
    {
        $goods_id = 0;
        if (isset ($this->param ['goods_id']) && $this->param ['goods_id'] != '') {
            $goods_id = $this->param['goods_id'];
            if (isset($this->param ['sale_price'] [0])) {
                $salePricedb = new SalePricedb ();
                $save_data ['market_price'] = $this->param ['sale_price'] [0];
                $save_data ['sale_price'] = $this->param ['sale_price'] [0];
                $save_data ['api_price'] = $this->param ['api_price'] [0];
                $save_data ['view_stock'] = $this->param ['view_stock'] [0];
                $save_data ['caigoujia'] = $this->param ['caigoujia'] [0];
                $save_data ['chengbenjia'] = $this->param ['chengbenjia'] [0];
                $save_data ['beizhu'] = $this->param ['beizhu'] [0];
                $salePricedb->where('goods_sku', $this->param ['goods_sku'])->update($save_data);
            }
            if (isset ($this->param ['goods_son_name'])) {
                $save_goods ['goods_son_name'] = $this->param ['goods_son_name'];
                $save_goods ['upc'] = $this->param ['upc'];
                $save_goods ['goods_name'] = $this->param ['goods_name'];
                $save_goods ['goods_model'] = $this->param ['goods_model'];
                $save_goods ['goods_keywords'] = $this->param ['goods_keywords'];
                $save_goods ['goods_unit'] = $this->param ['goods_unit'];
                $save_goods ['product_firm'] = $this->param ['product_firm'];
                $save_goods ['product_area'] = $this->param ['product_area'];
                $save_goods ['is_lock'] = $this->param ['is_lock'];
                if (isset($this->param['cid']) && in_array($this->param['cid'], ['D140215', 'D120325', 'D120338', 'D120303', 'D120322', 'D090103', 'D120307', 'D090111', 'D120328', 'D110112'])) {
                    $save_goods ['is_lock'] = 1;
                }
                // 验证根据品牌锁定商品
                if (isset($this->param['jun_brand_id'])) {
                    $get_brand_sign = Db::name('brand_api')->where('option', $this->param['jun_brand_id'])->value('brand_sign');
                    $save_goods ['is_lock'] = Db::name('brand')->where('brand_sign', $get_brand_sign)->value('is_lock_goods');
                }
                $save_goods ['api_price'] = $this->param ['g_api_price'];
                $save_goods ['sale_price'] = $this->param ['g_sale_price'];
                $save_goods ['goods_beizhu1'] = $this->param ['goods_beizhu1'];
                $save_goods ['goods_beizhu2'] = $this->param ['goods_beizhu2'];
                $save_goods ['goods_beizhu3'] = $this->param ['goods_beizhu3'];
                $save_goods ['goods_beizhu4'] = $this->param ['goods_beizhu4'];
                $save_goods ['goods_beizhu5'] = $this->param ['goods_beizhu5'];
                $save_goods ['goods_beizhu6'] = $this->param ['goods_beizhu6'];
                $save_goods ['goods_beizhu7'] = $this->param ['goods_beizhu7'];
                $save_goods ['goods_beizhu8'] = $this->param ['goods_beizhu8'];
                $save_goods ['goods_beizhu9'] = $this->param ['goods_beizhu9'];
                $save_goods ['goods_beizhu10'] = $this->param ['goods_beizhu10'];
                $save_goods ['goods_beizhu11'] = $this->param ['goods_beizhu11'];
                $save_goods ['goods_beizhu12'] = $this->param ['goods_beizhu12'];
                $save_goods ['goods_beizhu13'] = $this->param ['goods_beizhu13'];
                $save_goods ['goods_beizhu14'] = $this->param ['goods_beizhu14'];
                $save_goods ['goods_beizhu15'] = $this->param ['goods_beizhu15'];
                $save_goods ['code_69'] = $this->param['code_69'];
                $save_goods['sale_specifications'] = $this->param['sale_specifications'];
                $save_goods['standard_unit'] = $this->param['standard_unit'];
                if (isset ($this->param ['shuiwu_id'])) {
                    $save_goods ['shuiwu_id'] = $this->param ['shuiwu_id'];
                }
                if (isset ($this->param ['jun_id']) && $this->param ['jun_id']) {
                    $save_goods ['jun_id'] = $this->param ['jun_id'];
                }
                if (isset($this->param['check_area'])) {
                    $save_goods['check_area'] = $this->param['check_area'];
                }
                $this->useGlobalScope(false)->where('goods_sku', $this->param ['goods_sku'])->update($save_goods);

            }
        } else {
            // 验证重复采集
            $chk = $this->useGlobalScope(false)->where('goods_sku', $this->param ['goods_sku'])->find();
            // 处理分类
            $cid = $this->param ['cid'];
            $categorydb = new Categorydb ();
            $get_cid = $categorydb->useGlobalScope(false)->where('site_id', SITE_ID)->where('api_option', $cid)->find();
            if ($get_cid) {
                $get_cid = $get_cid->toArray();
                $this->param ['category_sign3'] = $get_cid ['category_sign'];
                if ($get_cid) {
                    $this->param['category_sign2'] = $get_cid['parent_sign'];
                }
            } else {
                $this->param ['category_sign3'] = 'a96051f3ecceaca2dc8d4c4b3e63fa27';
            }
            if ($chk) {
                $chk = $chk->toArray();
                $goods_id = $chk ['goods_id'];
                $this->param['jun_price_flag'] = 2;
                if (isset($this->param['sale_state']) && $this->param['sale_state'] !== 1) {
                    // 如果销售状态下架,清空库存
                    $save_data['view_stock'] = 0;
                    $this->param['view_stock'] = 0;
                } else {
                    // 开始：下架状态改成上架状态需要推送
                    if ($chk['sale_state'] !== 1) {
                        // 下架状态改成上架状态  推送
                        $this->param['goods_id'] = $chk['goods_id'];
                        $this->param['push_jun'] = 'yes';
                        $this->param ['view_stock'] [0] = 0;
                        $this->param['zhenshi'] = 0;
                    }
                    // 结束：下架状态改成上架状态需要推送
                }
                $this->allowField(true)->save($this->param, [
                    'goods_id' => $goods_id
                ]);
                $salePricedb = new SalePricedb ();
                $save_data ['market_price'] = $this->param ['sale_price'] [0];
                $save_data ['sale_price'] = $this->param ['sale_price'] [0];

                $salePricedb->where('goods_sku', $chk['goods_sku'])->where('site_id', 117)->update($save_data);

            } else {
                $this->allowField(true)->save($this->param);
                $goods_id = $this->getLastInsID();
                $salePricedb = new SalePricedb ();
                $save_data ['market_price'] = $this->param ['sale_price'] [0];
                $save_data ['sale_price'] = $this->param ['sale_price'] [0];
                $save_data ['api_price'] = $this->param ['api_price'] [0];
                $save_data ['view_stock'] = $this->param ['view_stock'] [0];
                $save_data ['site_id'] = 117;
                $save_data ['partner_id'] = 25;
                $save_data ['goods_sku'] = $this->param ['goods_sku'];
                $save_data ['give_score'] = 0;
                $save_data ['view_stock'] = 0;
                $save_data ['sale_attr_price_name'] = '商品价格';
                $save_data ['sale_price_sign'] = md5(time() . uniqid());

                $salePricedb->insert($save_data);
            }
            Cache::clear('goods');
        }
        $ugoodsdb = new UGoodsdb();
        $ugoodsdb->chkGoods($goods_id);
        Cache::clear('goods');
        if (isset ($this->param ['goods_id']) && $this->param ['goods_id'] != '' && isset($this->param['push_jun']) && $this->param['push_jun'] == 'yes') {
            // 推送重点商品报价
            $temp ['sku'] = $this->param ['goods_sku'];
            $temp ['price'] = $this->param ['api_price'] [0];
            $temp ['stock'] = $this->param ['view_stock'] [0];
            $temp['linkurl'] = 'http://tailongjipc.dixintong.com/goods_detail.html?goods_sku=' . $this->param['goods_id'];
            $temp['eccode'] = $this->param['goods_id'];
            $temp['linkprice'] = $this->param ['market_price'] [0];
            $temp['upc'] = $this->param['code_69'];
            $temp['saleSpecifications'] = $this->param['sale_specifications'];
            $temp['standardUnit'] = $this->param['standard_unit'];
            $post_json ['priceList'] = array();
            array_push($post_json ['priceList'], $temp);
            $jun_api = new Api ();
            $result = $jun_api->ajaxCountPrice($post_json);
            $this->jun_push_result = $result;
            $junapidb = new Junapidb ();
            $junapidb->param ['goods_sku'] = $temp ['sku'];
            $junapidb->param ['send_json'] = $post_json;
            $junapidb->param ['result_json'] = $result;
            $junapidb->ajaxSave();
            $goodsdb = new Goodsdb ();
            $goodsdb->where('goods_id', $this->param ['goods_id'])->update([
                'is_push' => $result['isSuccess'] == true ? 1 : 2
            ]);

            // 商品价格日志开始
            $goods_log_data = [];
            $goods_log_data['goods_sku'] = $this->param ['goods_sku'];
            $goods_log_data['date'] = date('Y-m-d H:i:s');
            $goods_log_data['types'] = '产品详情报价';
            $temp_son = [];
            $temp_son['用户'] = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
            $temp_son['参考价'] = $this->param['sale_price'][0] ?? 0;
            $temp_son['报价'] = $this->param['api_price'][0] ?? 0;
            $temp_son['最低价'] = Db::name('sale_price')->where('goods_sku', $this->param['goods_sku'])->value('zuidijia');
            $temp_son['成本'] = $this->param['caigoujia'][0] ?? 0;
            $temp_son['真实库存'] = $this->param['zhenshi'] ?? Db::name('goods')->where('goods_sku', $this->param['goods_sku'])->value('zhenshi');
            $temp_son['库存'] = $this->param['view_stock'][0] ?? 0;
            $temp_son['结果'] = $result['priceList'][0]['reason'];
            $goods_log_data['params'] = json_encode($temp_son, JSON_UNESCAPED_UNICODE);
            $goodsPriceLogdb = new GoodsPriceLogdb();
            $goodsPriceLogdb->save($goods_log_data);
            // 商品价格日志结束
            Cache::clear('goods');
            return 'success';
        }

        return 'success';
    }

    // 保存
    public function ajaxSave()
    {
        $rule = new Goodsrule ();
        $this->param ['partner_id'] = PARTNER_ID;
        if (isset ($this->param ['site_id'])) {
            if ($this->param ['site_id'] == 0 || $this->param ['site_id'] == '') {
                $this->param ['site_id'] = null;
            } else {
                $this->param ['site_id'] = $this->param ['site_id'];
            }
        } else {
            if (!empty (SITE_ID)) {
                $this->param ['site_id'] = SITE_ID;
            } else {
                $this->param ['site_id'] = null;
            }
        }
        if (!$rule->check($this->param)) {
            return $rule->getError();
        }
        if (isset ($this->param ['goods_id']) && $this->param ['goods_id'] != '') {
            $before_data = $this->ajaxFind($this->param ['goods_sku']);
            $this->param['category_sign3'] = $this->param['category_sign3'] ?? $before_data['category_sign3'];
            $this->param['category_sign2'] = $this->param['category_sign2'] ?? $before_data['category_sign2'];
            $this->param['category_sign1'] = $this->param['category_sign1'] ?? $before_data['category_sign1'];
        } else {
            $before_data = $this->param;
        }

        // 开始保存数据 采用事务功能
        Db::startTrans();
        // SHA開頭的訂單號屬於重點商品
        if (strpos($this->param['goods_sku'], 'SHA') !== false) {
            $this->param['callet_juncai'] = 1;
        }
        // 結束
        if (isset ($this->param ['goods_id']) && $this->param ['goods_id'] != '') {
            // 修改 接口采集设置2
            $this->allowField(true)->save($this->param, [
                'goods_id' => $this->param ['goods_id']
            ]);
        } else {
            $this->allowField(true)->save($this->param);
        }
        $this->last_goods_sku = $this->param ['goods_sku'];
        // 保存属性
        $attrValuedb = new AttrValuedb ();
        $attrValuedb->param = $this->param;
        $return = $attrValuedb->ajaxSave();
        if ($return != 'success') {
            Db::rollback();
            return $return;
        }
        // 保存销售属性
        $saleAttrdb = new SaleAttrdb ();
        $saleAttrdb->param = $this->param;
        $return = $saleAttrdb->ajaxSave();
        if ($return != 'success') {
            Db::rollback();
            return $return;
        }
        // 保存销售价格
        $salePricedb = new SalePricedb ();
        $salePricedb->param = $this->param;
        $return = $salePricedb->ajaxSave();
        if ($return != 'success') {
            Db::rollback();
            return $return;
        }
        if (isset ($this->param ['is_audit']) && $this->param ['is_audit'] == 'true') {
            $is_audit = 'yes';
        } else {
            $is_audit = 'no';
        }
        // 同步到分站信息 这里保证只有主站存在push_to_site
        if (isset ($this->param ['push_to_site']) && $this->param ['push_to_site'] == 'on') {
            $get_sku_list = $this->useGlobalScope(false)->where('goods_sku', $this->param ['goods_sku'])->select();
            if ($get_sku_list) {
                $get_sku_list = $get_sku_list->toArray();
                foreach ($get_sku_list as $key => $val) {
                    if ($val ['site_id'] == null) {
                        continue;
                    }
                    $this->param = array();
                    $this->param ['site_id'] = 0;
                    $this->param ['select_site_id'] = $val ['site_id'];
                    $this->param ['goods_sku'] = $val ['goods_sku'];
                    $this->copy();
                }
            }
        }

        Db::commit();
        if (isset ($this->param ['goods_id']) && $this->param ['goods_id'] != '') {
            $goods_id = $this->param ['goods_id'];
        } else {
            $goods_id = $this->getLastInsID();
        }

        // 同步到优仕分系统
        $ugoodsdb = new UGoodsdb();
        $ugoodsdb->chkGoods($goods_id);
        $this->writePriceRecord($this->param ['goods_sku']);
        // 写推送通知
        $get_audit = $this->useGlobalScope(false)->where('goods_sku', $this->param ['goods_sku'])->find()->toArray();
        if (isset ($this->param ['goods_id']) && $this->param ['goods_id']) {
            // 修改价格
            if (number_format($this->param ['api_price'] [0], 2, '.', '') != number_format($before_data ['api_price'], 2, '.', '')) {
                $postNoticedb = new PostNoticedb ();
                $postNoticedb->param ['post_type'] = 2;
                $postNoticedb->param ['sku_order_no'] = $this->param ['goods_sku'];
                $postNoticedb->param ['old_data'] = $this->param ['market_price'] [0];
                $postNoticedb->param ['new_data'] = $this->param ['api_price'] [0];
                if ($get_audit ['audit_state'] != 1) {
                    $postNoticedb->param ['is_audit'] = 2;
                }
                $postNoticedb->ajaxSave();
            }
            // 修改内容
            if ($this->param ['goods_content'] != $before_data ['goods_content']) {
                $postNoticedb = new PostNoticedb ();
                $postNoticedb->param ['post_type'] = 16;
                $postNoticedb->param ['sku_order_no'] = $this->param ['goods_sku'];
                $postNoticedb->ajaxSave();
            }
            // 修改属性
            foreach ($before_data ['attr_value'] as $key => $val) {
                if (isset ($this->param [$key])) {
                    if ($val != $this->param [$key]) {
                        $postNoticedb = new PostNoticedb ();
                        $postNoticedb->param ['post_type'] = 16;
                        $postNoticedb->param ['sku_order_no'] = $this->param ['goods_sku'];
                        $postNoticedb->param ['old_data'] = $val;
                        $postNoticedb->param ['new_data'] = $this->param [$key];
                        if ($get_audit ['audit_state'] != 1) {
                            $postNoticedb->param ['is_audit'] = 2;
                        }
                        $postNoticedb->ajaxSave();
                        break;
                    }
                }
            }
            // 上下架
            if (isset ($this->param ['sale_state']) && $this->param ['sale_state'] == 'on') {
                $new_sale_state = true;
            } else {
                $new_sale_state = false;
            }
            if ($new_sale_state != $before_data ['sale_state']) {
                $postNoticedb = new PostNoticedb ();
                $postNoticedb->param ['post_type'] = 4;
                $postNoticedb->param ['sku_order_no'] = $this->param ['goods_sku'];
                $postNoticedb->param ['old_data'] = $before_data ['sale_state'] ? 1 : 2;
                $postNoticedb->param ['new_data'] = $new_sale_state ? 1 : 2;
                if (isset($this->param['jun_update']) && $this->param['jun_update']) {
                    $postNoticedb->param['jun_update'] = $this->param['jun_update'];
                }
                if ($get_audit ['audit_state'] != 1) {
                    $postNoticedb->param ['is_audit'] = 2;
                }
                $postNoticedb->ajaxSave();
            }
        } else {
            // 新增 写推送通知
            $postNoticedb = new PostNoticedb ();
            $postNoticedb->param ['post_type'] = 6;
            $postNoticedb->param ['sku_order_no'] = $this->param ['goods_sku'];
            $postNoticedb->param ['new_data'] = 1;
            if (isset($this->param['jun_update']) && $this->param['jun_update']) {
                $postNoticedb->param['jun_update'] = $this->param['jun_update'];
            }
            if (isset ($this->param ['is_audit']) && $this->param ['is_audit'] == 'true') {
                $postNoticedb->param ['is_audit'] = 2;
            }
            $postNoticedb->ajaxSave();
        }

        // 分站修改数据需要审核
        if ($is_audit == 'yes') {
            $auditdb = new Auditdb ();
            $auditdb->param ['audit_method'] = 3;
            if (isset ($this->param ['goods_id']) && $this->param ['goods_id'] != '') {
                $auditdb->param ['audit_type'] = 2;
            } else {
                $auditdb->param ['audit_type'] = 1;
            }
            $auditdb->param ['site_id'] = SITE_ID;
            $auditdb->param ['supplier_id'] = MEMBER_ID;
            $auditdb->param ['before_option'] = $before_data;
            $auditdb->param ['old_option'] = json_encode($before_data);
            // $auditdb->param['save_option'] = json_encode($this->param);
            $after_data = $this->ajaxFind($this->param ['goods_sku']);
            $auditdb->param ['after_option'] = $after_data;
            $auditdb->param ['audit_sign'] = $this->param ['goods_sku'];
            if (isset($this->param['jun_update']) && $this->param['jun_update']) {
                $auditdb->param['jun_update'] = $this->param['jun_update'];
            }
            $audit_state = $auditdb->ajaxSave();
            if ($audit_state == 'fail') {
//				$this->save ( [
//						'audit_state' => $before_data ['audit_state']
//				], [
//						'goods_id' => $before_data ['goods_id']
//				] );
                $this->save([
                    'audit_state' => $before_data ['audit_state']
                ], [
                    'goods_id' => $before_data ['goods_id']
                ]);
            }
            Cache::clear('goods');
            return 'success';
        }
        if (SITE_ID == 117 && isset($this->param['push_jun']) && $this->param['push_jun'] == 'yes' && !isset ($this->param ['is_supplier'])) {
            // 军采推送
            if ($get_audit['audit_state'] == 1) {
                $jun_api = new Api ();
                $post_json = array();
                if (isset($this->param['jun_update']) && $this->param['jun_update']) {
                    $temp ['sku'] = $this->last_goods_sku;
                    $temp ['updateType'] = $this->param['jun_update'];
                    array_push($post_json, $temp);
                } else {
                    if (isset ($this->param ['goods_id']) && $this->param ['goods_id']) {
                        $after_data = Db::name('goods')->where('goods_id', $this->param['goods_id'])->find();
                        if ($after_data['is_push'] == 2) {
                            $temp ['sku'] = $this->last_goods_sku;
                            $temp ['updateType'] = 1;
                            array_push($post_json, $temp);
                            $this->update(array('is_push' => 1), ['goods_id' => $this->param['goods_id']]);
                        } else {
                            $this->update(array('is_push' => 1), ['goods_id' => $this->param['goods_id']]);
                            $temp ['sku'] = $this->last_goods_sku;
                            $temp ['updateType'] = 2;
                            array_push($post_json, $temp);
                            $temp ['sku'] = $this->last_goods_sku;
                            $temp ['updateType'] = 3;
                            array_push($post_json, $temp);
                            $temp ['sku'] = $this->last_goods_sku;
                            $temp ['updateType'] = 4;
                            array_push($post_json, $temp);
                            $temp ['sku'] = $this->last_goods_sku;
                            $temp ['updateType'] = 5;
                            array_push($post_json, $temp);
                            $temp ['sku'] = $this->last_goods_sku;
                            $temp ['updateType'] = 6;
                            array_push($post_json, $temp);
                        }
                    } else {
                        $temp ['sku'] = $this->last_goods_sku;
                        $temp ['updateType'] = 1;
                        array_push($post_json, $temp);
                    }
                }
                $return_json = $jun_api->ajaxproductupdateinfo($post_json);
                $this->jun_push_result = $return_json;
                $junapidb = new Junapidb ();
                $junapidb->param ['goods_sku'] = $temp ['sku'];
                $junapidb->param ['send_json'] = $post_json;
                $junapidb->param ['result_json'] = $return_json;
                $junapidb->ajaxSave();
            }
        }
        Cache::clear('goods');
        return 'success';
    }

    // 导入保存
    public function ajaxSaveAll()
    {
        $rule = new Goodsrule ();
        Db::startTrans();
        foreach ($this->param as $k => $v) {
            if (isset ($this->param [$k] ['flag_i'])) {
                $flag_i = '，请检查EXCEl第' . $this->param [$k] ['flag_i'] . '行';
            } else {
                $flag_i = '';
            }
            $this->param [$k] ['partner_id'] = PARTNER_ID;
            $this->param [$k] ['site_id'] = SITE_ID;
            if (!$rule->check($this->param [$k])) {
                return $rule->getError() . $flag_i;
            }
            $before_data = $this->param [$k];
            unset ($this->goods_id);
            $this->allowField(true)->isUpdate(false)->save($this->param [$k]);

            // 保存属性
            $attrValuedb = new AttrValuedb ();
            $attrValuedb->param = $this->param [$k];
            $attrValuedb->param ['site_id'] = $this->get_site_id;
            $return = $attrValuedb->ajaxSave();
            if ($return != 'success') {
                Db::rollback();
                return $return . $flag_i;
            }

            // 保存销售属性
            $saleAttrdb = new SaleAttrdb ();
            $saleAttrdb->param = $this->param [$k];
            $saleAttrdb->param ['site_id'] = $this->get_site_id;
            $return = $saleAttrdb->ajaxSave();
            if ($return != 'success') {
                Db::rollback();
                return $return . $flag_i;
            }
            // 保存销售价格
            $salePricedb = new SalePricedb ();
            $salePricedb->param = $this->param [$k];
            $salePricedb->param ['site_id'] = $this->get_site_id;
            $return = $salePricedb->ajaxSave();
            if ($return != 'success') {
                Db::rollback();
                return $return . $flag_i;
            }
            if (SITE_ID) {
                $sitedb = new Sitedb ();
                $get_site = $sitedb->ajaxFind(SITE_ID);
                if ($get_site ['goods_audit'] == 1) {
                    $auditdb = new Auditdb ();
                    $auditdb->param ['audit_method'] = 3;
                    $auditdb->param ['audit_type'] = 1;
                    $auditdb->param ['site_id'] = SITE_ID;
                    $auditdb->param ['before_option'] = $before_data;
                    $auditdb->param ['old_option'] = json_encode($before_data);
                    // $auditdb->param['save_option'] = json_encode($this->param);
                    $after_data = $this->ajaxFind($this->param [$k] ['goods_sku']);
                    $auditdb->param ['after_option'] = $after_data;
                    $auditdb->param ['audit_sign'] = $this->param [$k] ['goods_sku'];
                    $audit_state = $auditdb->ajaxSave();
                    if ($audit_state == 'fail') {
                        $this->save([
                            'audit_state' => $before_data ['audit_state']
                        ], [
                            'goods_id' => $before_data ['goods_id']
                        ]);
                    }
                }
            }
        }
        Db::commit();
        Cache::clear('goods');
        foreach ($this->param as $k => $v) {
            $this->writePriceRecord($this->param [$k] ['goods_sku']);
            // 新增 写推送通知
            $postNoticedb = new PostNoticedb ();
            $postNoticedb->param ['post_type'] = 6;
            $postNoticedb->param ['sku_order_no'] = $this->param [$k] ['goods_sku'];
            $postNoticedb->param ['new_data'] = 1;
            $postNoticedb->param ['is_audit'] = 2;
            $postNoticedb->ajaxSave();
        }

        return 'success';
    }

    // 软删除
    public function ajaxDelete()
    {
        $jddb = new Jddb();
        if (!isset ($this->param ['goods_id'])) {
            $get_goods = $this->where('goods_sku', 'in', $this->param ['goods_sku'])->select()->toArray();
            $goods_ids = array();
            foreach ($get_goods as $key => $val) {
                array_push($goods_ids, $val ['goods_id']);
                $jddb->ajaxDelete($val['goods_sku']);
            }
            if (count($goods_ids)) {
                $sql = $this->destroy($goods_ids, true);
                Cache::clear('goods');
            }
        } else {
            $get_goods = $this->where('goods_id', $this->param ['goods_id'])->find()->toArray();
            if (isset ($this->param ['delete']) && $this->param ['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('goods_id', 'IN', $get_goods ['goods_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('goods_id', 'IN', $this->param ['goods_id']);
                }, true);
            }
            $jddb->ajaxDelete($get_goods['goods_sku']);
            $postNoticedb = new PostNoticedb ();
            $postNoticedb->param ['post_type'] = 6;
            $postNoticedb->param ['sku_order_no'] = $get_goods ['goods_sku'];
            $postNoticedb->param ['new_data'] = 2;
            $postNoticedb->ajaxSave();
            Cache::clear('goods');
        }
        if (isset ($this->param ['category_sign']) || isset ($this->param ['goods_sku'])) {
            if (isset ($this->param ['site_id'])) {
                $this->where('site_id', $this->param ['site_id'])->delete();
                Cache::clear('goods');
            }
        }
    }

    public function writePriceRecord($goods_sku)
    {
        $salePricedb = new SalePricedb ();
        $salePricedb->param ['goods_sku'] = $goods_sku;
        $salePricedb->param ['site_id'] = -1;
        $data = $salePricedb->ajaxList();
        $priceRecorddb = new PriceRecorddb ();
        $priceRecorddb->param ['goods_sku'] = $goods_sku;
        foreach ($data as $key => $val) {
            $priceRecorddb->param ['market_price'] = $val ['market_price'];
            $priceRecorddb->param ['sale_price'] = $val ['sale_price'];
            $priceRecorddb->param ['api_price'] = $val ['api_price'];
            $priceRecorddb->param ['site_id'] = $val ['site_id'];
            $priceRecorddb->ajaxSave();
        }
    }

    // 获取商品封面
    public function getGoodsImageAttr($value, $row)
    {
        $uploaddb = new Uploaddb();
        if ($row['goods_picture']) {
            $img = $uploaddb->getFind($row['goods_picture']);
        } else {
            if ($row['goods_pictures']) {
                $temp = explode(',', $row ['goods_pictures']);
                $img = $uploaddb->getFind($temp[0]);
            }
        }
        return $img['save_path'] ?: '';
    }

    // 获取商品图片
    public function getGoodsImagesAttr($value, $row)
    {
        $uploaddb = new Uploaddb();
        $imgs = [];
        if ($row['goods_pictures']) {
            $temp = explode(',', $row ['goods_pictures']);
            $imgs = $uploaddb->getSelect($temp);
        }
        $result = [];
        foreach ($imgs as $key => $val) {
            if (isset($val['save_path']) && $val['save_path']) {
                array_push($result, $val['save_path']);
            }
        }
        return $result;
    }

    // 获取分类名称
    public function getCategoryNameAttr($value, $row)
    {
        $get_category = Db::name('category')->where('category_sign', $row['category_sign'] ?? $row['category_id'])->value('category_name');
        return $get_category ?: '';
    }

    // 获取品牌名称
    public function getBrandNameAttr($value, $row)
    {
        $option = json_decode($row['api_option'], true);
        if (isset($option['brandid'])) {
            return Db::name('brand_api')->where('option', $option['brandid'])->value('brand_name');
        } else {
            $get_brand = Db::name('brand')
                ->where('brand_sign', $row['brand_sign'] ?? $row['brand_id'])
                ->value('brand_name');
            return $get_brand ?: '';
        }
    }


    public function ajaxFrontList()
    {
        $data = $this
            //->fetchSql(true)
            ->order($this->param['_o'], $this->param['_b'])
            ->whereNotNull('sale_price')
            ->page($this->param['page'], $this->param['limit'])
            ->field('goods_id,goods_sku,goods_name,goods_model,sale_price,sale_num')
            ->select();
        return $data;
    }

    // 数据处理
    protected function handleData($val)
    {
        $categorydb = new Categorydb ();
        $branddb = new Branddb ();
        $uploaddb = new Uploaddb ();
        $salePricedb = new SalePricedb ();
        $saleAttrdb = new SaleAttrdb ();
        foreach ($val as $k => $v) {
            $val [$k] = $v;
            switch ($k) {
                case 'goods_id':
                    if (isset($this->param['need_gys']) && $this->param['need_gys'] == 'yes') {
                        // 验证获取信息是否和购物车下的价格一致
                        $cartdb = new Cartdb();
                        $get_cart = $cartdb->where('order_no', $this->param['order_no'])->where('goods_sku', $val['goods_sku'])->find();
                        $baojiadb = new Baojiadb();
                        $get_last_baojia = $baojiadb
                            ->where('goods_id', $v)
                            ->whereTime('create_time', '<', $get_cart['create_time'])
                            ->order('baojia_id', 'desc')
                            ->find();

                        $val['gongyingshang'] = '';
                        $val['yewuyuan'] = '';
                        $val['shenqingtime'] = '';
                        if ($get_last_baojia) {

                            if ($get_cart && $get_cart['goods_price'] == $get_last_baojia['baojia']) {
                                $memberdb = new Memberdb();
                                $get_gys = $memberdb->where('member_id', $get_last_baojia['apply_member_id'])->find();
                                if ($get_gys) {
                                    $val['gongyingshang'] = $get_gys['supplier_name'];
                                    $val['yewuyuan'] = $get_last_baojia['beizhu'];
                                    $val['shenqingtime'] = $get_last_baojia ['create_time'];
                                }
                            }
                        }
                    }
                    break;
                case 'sale_price' :
                    $val ['g_sale_price'] = $v;
                    break;
                case 'api_price' :
                    $val ['g_api_price'] = $v;
                    break;
                case 'category_sign3' :
                    $get_category = $categorydb->where('category_sign', $v)->find();
                    $val ['category_name'] = $get_category ['category_name'] ?: '';
                    $val ['category_name3'] = $get_category ['category_name'] ?: '';
                    $val ['category_api_option'] = $get_category ['api_option'] ?: '';
                    break;
                case 'category_sign2' :
                    if (isset($this->param['need_category2'])) {
                        $get_category = $categorydb->where('category_sign', $v)->find();
                        $val ['category_name2'] = $get_category ['category_name'] ?: '';
                    }
                    break;
                case 'category_sign1' :
                    if (isset($this->param['need_category1'])) {
                        $get_category = $categorydb->where('category_sign', $v)->find();
                        if (isset ($get_category ['category_name']))
                            $val ['category_name1'] = $get_category ['category_name'];
                        else
                            $val ['category_name1'] = '';
                    }
                    break;
                case 'brand_sign' :
                    if (isset($this->param['pre_info']) && $this->param['pre_info'] == 'utec') {
                        $get_brand = $branddb->where('brand_sign', $v)->find();
                        if (isset ($get_brand ['brand_name']))
                            $val ['brand_name'] = $get_brand ['brand_name'];
                        else
                            $val ['brand_name'] = '';
                        if (isset ($get_brand ['api_option'])) {
                            $val ['brand_api_option'] = $get_brand ['api_option'];
                        } else {
                            $val ['brand_api_option'] = '';
                        }
                    }
                    break;
                case 'goods_pictures' :
                    if (!isset ($this->param ['no_more_price'])) {
                        if ($val ['goods_picture']) {
                            $val ['goods_picture'] = $uploaddb->getFind($val['goods_picture']);
                            if ($val['goods_pictures']) {
                                $temp = explode(',', $val ['goods_pictures']);
                                $val ['goods_pictures'] = $uploaddb->getSelect($temp);
                            } else {
                                $val ['goods_pictures'] = $uploaddb->getSelectTemp();
                            }
                        } else {
                            $temp = explode(',', $val ['goods_pictures']);
                            $val ['goods_picture'] = $uploaddb->getFind($temp [0]);
                            $val ['goods_pictures'] = $uploaddb->getSelect($temp);
                        }
                    } else {
                        if (!isset ($this->param ['no_need_picture'])) {
                            if ($val ['goods_picture']) {
                                $val ['goods_picture'] = $uploaddb->getFind($val ['goods_picture']);
                            } else {
                                $temp = explode(',', $val ['goods_pictures']);
                                $val ['goods_picture'] = $uploaddb->getFind($temp [0]);
                                $val ['goods_pictures'] = $uploaddb->getSelect($temp);


                            }
                        }
                    }
                    break;

                case 'is_real' :
                    $val ['is_real'] = $val ['is_real'] == 1 ? true : false;
                    break;
                case 'is_copy' :
                    $val ['is_copy'] = $val ['is_copy'] == 1 ? true : false;
                    break;
                case 'is_shopping' :
                    $val ['is_shopping'] = $val ['is_shopping'] == 1 ? true : false;
                    break;
                case 'is_install' :
                    $val ['is_install'] = $val ['is_install'] == 1 ? true : false;
                    break;
                case 'sale_state' :
                    $val ['sale_state'] = $val ['sale_state'] == 1 ? true : false;
                    break;
                case 'is_energy' :
                    $val ['is_energy'] = $val ['is_energy'] == 1 ? true : false;
                    break;
                case 'is_environmental' :
                    $val ['is_environmental'] = $val ['is_environmental'] == 1 ? true : false;
                    break;
                case 'view_times' :
                    $val ['view_times'] = $this->getGoodsViewTimes($val ['goods_id']);
                    break;
                case 'api_option' :
                    $val ['goods_api_option'] = json_decode($v, true);
                    if (isset ($this->param ['pre_info']) && $this->param ['pre_info'] == 'jun') {
                        if (isset ($val ['goods_api_option'] ['brand'])) {
                            $brand_id = $val ['goods_api_option'] ['brand'];
                        } else {
                            $brand_id = $val ['goods_api_option'] ['brandid'];
                        }
                        $val ['jun_brand_name'] = '无';
                        $brand_api = new BrandApidb ();
                        $get_brand_api = $brand_api->useGlobalScope(false)->where('option', $brand_id)->find();
                        if ($get_brand_api) {
                            $get_brand_api = $get_brand_api->toArray();
                            $get_brand_info = $branddb->useGlobalScope(false)->where('brand_sign', $get_brand_api ['brand_sign'])->find();
                            if ($get_brand_info) {
                                $get_brand_info = $get_brand_info->toArray();
                                $val ['jun_brand_name'] = $get_brand_info ['brand_name'];
                            }
                        }
                    }

                    break;
                case 'goods_content' :
                    $request = request();
                    if (isset ($request->param() ['config'])) {
                        $config = $request->param() ['config'];
                        if (isset ($config ['is_app']) && $config ['is_app'] == true) {
                            $val ['goods_content'] = str_replace('"/static', '"' . $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/static', $val ['goods_content']);
                            $val ['goods_content'] = str_replace('<img', '<img style="max-width:100%"', $val ['goods_content']);
                        }
                    }
                    break;
                case 'is_lock' :
                    if ($v == 1) {
                        if ($val ['lock_open_time'] <= time()) {
                            $val ['is_lock'] = 1;
                        }
                    }
                    break;
                case 'admin_id':
                    if ($v) {
                        $val['faburen'] = '';
                        if (isset ($this->param ['pre_info']) && $this->param ['pre_info'] == 'utec') {
                            $get_member = Memberdb::where('member_id', $v)->find();
                            if ($get_member) {
                                $get_member = $get_member->toArray();
                                $val['faburen'] = $get_member['supplier_name'] ? $get_member['supplier_name'] : $get_member['username'];
                            }
                        }
                    }
                    break;
                default :
                    break;
            }
        }
        // 获取发票证书申请中的管理部门
        $val['manage_department'] = $this->manageDepartmentAttr($val);

        // 获取发票证书申请中的管理部门
        $val['manage_department'] = $this->manageDepartmentAttr($val);

        // 销售属性
        if (!isset ($this->param ['no_more_price'])) {
            $val ['sale_attr'] = $saleAttrdb->ajaxSelect($val ['goods_sku']);
        }

        // 获取前端显示价格
        $salePricedb->param ['goods_sku'] = $val ['goods_sku'];
        if (isset ($this->param ['site_id']) && $this->param ['site_id'] == -1) {
            $salePricedb->param ['site_id'] = $val ['site_id'];
        } else {
            $salePricedb->param ['site_id'] = $this->get_site_id;
        }
        if (isset ($this->param ['the_goods_site'])) {
            $salePricedb->param ['site_id'] = $val ['site_id'];
        }
        if (isset ($this->param ['no_more_price'])) {
            $salePricedb->param ['no_more_price'] = $this->param ['no_more_price'];
        }
        $val ['sale_price_info'] = $salePricedb->ajaxSelect();
        foreach ($val['sale_price_info']['data'] as $k1 => $v1) {
            $val['sale_price_info']['data'][$k1]['jun_state'] = $val['jun_state'];
        }
        $val ['market_price'] = $val ['sale_price_info'] ['min_market_price'];
        $val ['sale_price'] = $val ['sale_price_info'] ['min_sale_price'];
        $val ['api_price'] = $val ['sale_price_info'] ['min_api_price'];
        $val ['view_stock'] = $val ['sale_price_info'] ['view_stock'];
        $val ['caigoujia'] = $val ['sale_price_info'] ['caigoujia'];
        $val ['zuidijia'] = $val ['sale_price_info'] ['zuidijia'];
        $val ['jun_zuidijia'] = $val ['sale_price_info'] ['jun_zuidijia'];
        $val ['chengbenjia'] = $val ['sale_price_info'] ['chengbenjia'];
        $val ['beizhu'] = $val ['sale_price_info'] ['beizhu'];

        if (isset($this->param['lastbaojia']) && $this->param['lastbaojia']) {
            // 获取最后报价时间 这里占用时间1.5m
            $baojiadb = new Baojiadb();
            $get_baojia = $baojiadb->where('goods_id', $val['goods_id'])->order('baojia_id', 'desc')->value('create_time');
            $val ['lastbaojia'] = $get_baojia ? date('Y-m-d H:i', $get_baojia) : '';
            if (date('Y-m-d', $val['jun_last_time']) == date('Y-m-d')) {
                $val['lastbaojia'] = date('Y-m-d H:i', $val['jun_last_time']);
            }
        }
        // 处理报价报警
        $abs_price = $val ['g_sale_price'] - $val ['g_api_price'];
        $val ['price_warm'] = 0;
        if ($abs_price == 0) {
            $val ['price_warm'] = 1; // 10% 以内
        } elseif ($abs_price < 0) {
            $val ['price_warm'] = 3; // 高于限价
        } else {
            $t = $abs_price / $val ['g_sale_price'] * 100;
            if ($t > $this->config_baojing) {
                $val ['price_warm'] = 2; // 大于10%
            } else {
                $val ['price_warm'] = 1; // 10% 以内
            }
        }

        if (isset ($this->param ['need_attr'])) {
            // 分类属性值
            $attrValuedb = new AttrValuedb ();
            $val ['attr_value'] = $attrValuedb->ajaxSelect($val ['goods_sku']);
            // 分类属性
            $attrdb = new Attrdb ();
            $attrdb->param ['category_sign'] = $val ['category_sign3'];
            $category_attr = $attrdb->ajaxList();
            $attr_arr = array();
            foreach ($category_attr as $k => $v) {
                $attr_arr [$k] ['group_name'] = $v ['group_name'];
                $attr_arr [$k] ['attr_name'] = $v ['attr_name'];
                if (isset ($val ['attr_value'] [$v ['attr_sign']])) {
                    $attr_arr [$k] ['attr_value'] = $val ['attr_value'] [$v ['attr_sign']];
                } else {
                    $attr_arr [$k] ['attr_value'] = '';
                }
            }
            $val ['goods_attr'] = $attr_arr;
        }
        return $val;
    }

    public function salePrice()
    {
        return $this->hasMany(SalePricedb::Class, 'goods_sku', 'goods_sku');
    }
}